<template>
  <div class="inner">
    <transition name="slide">
      <div class="slide" v-show="toggleShow">
        <div class="slide-header">
          <div class="middle-create-btn" @click="addSession">
            <img src="@img/middle/jiahao.png" alt="" />
            <p>创建会话</p>
          </div>
        </div>
        <div class="slide-content" ref="scrollRef" @scroll="handleScroll">
          <div
            class="middle-list"
            v-for="key in chatStore.menuList"
            :key="key.name"
          >
            <div class="list-item" v-if="key.list?.length > 0">
              <p>{{ key.name }}</p>
              <ul>
                <li
                  v-for="item in key.list"
                  :key="item.id"
                  :class="{ active: item.id == iconIndex }"
                  @click="tabChange(item.id)"
                >
                  <div class="item-not-edit" v-if="!editingStatus[item.id]">
                    <div class="item-left">
                      <img
                        src="@img/middle/dialogue-active.png"
                        v-if="item.id == iconIndex"
                      />
                      <img src="@img/middle/dialogue.png" v-else />
                      <div class="item-left-text">
                        <p>{{ item.question }}</p>
                      </div>
                    </div>
                    <div class="item-right" v-if="item.id == iconIndex">
                      <img
                        src="@img/middle/edit.png"
                        @click.stop="showEdit(item.id)"
                      />
                      <img
                        src="@img/middle/delete.png"
                        @click.stop="deleteData(item.id)"
                      />
                    </div>
                  </div>

                  <div class="item-edit" v-else>
                    <input @click.stop type="text" v-model="item.question" />
                    <div class="img-container">
                      <img
                        @click.stop="editData(item.id, item.question)"
                        src="@img/middle/edit.png"
                      />
                    </div>
                  </div>
                </li>
              </ul>
            </div>
          </div>
        </div>
        <div class="slide-footer"></div>
      </div>
    </transition>

    <div class="toggle" @click="toggleContent" ref="toggleRef">
      <img src="@img/middle/retract.png" alt="" />
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, nextTick, watch } from "vue";
import router from "@router";
// api
import { chatList, chatUpdate, chatDelete, chatSave } from "@api/chat";
// stores
import { useGlobalStore } from "@stores";
const globalStore = useGlobalStore();
const userStore = globalStore.userStore;
const chatStore = globalStore.chatStore;
// 节流
import { throttle } from "@utils/tools";

// 创建会话
const addSession = async () => {
  const res = await chatSave({
    userId: userStore.userInfo.userId,
    type: chatStore.menuId,
  });
  if (res.code !== 0) return;

  chatStore.menuList[0].list.unshift({
    id: res.data.chatId,
    userId: userStore.userInfo.userId,
    question: "智能对话",
    type: chatStore.menuId,
    assistantId: null,
    identity: null,
    occupation: null,
    workTime: null,
    technology: null,
    dateType: "1",
    created: "",
    updated: "",
  });
  router.push({
    path: "/chat",
    query: {
      id: res.data.chatId,
    },
  });
};
const toggleShow = ref(true);
const toggleRef = ref<HTMLElement | null>(null);
const toggleContent = () => {
  toggleShow.value = !toggleShow.value;
  if (toggleShow.value) {
    // 显示
    toggleRef.value.style.transform = "translateX(185px)  rotate(0)";
  } else {
    // 隐藏
    toggleRef.value.style.transform = "translateX(-12px)  rotate(180deg)";
  }
};
// 选中会话列表
const iconIndex = ref(0);

const itemHeight = ref<number>(39);
const scrollRef = ref(null);

// 查询用户提问会话列表
const getChatList = async () => {
  await nextTick();
  // 计算可视区能放多少个dom   可视区的高度 / 单个高度   + 1
  const pageSize =
    Math.floor(scrollRef.value?.clientHeight / itemHeight.value) + 1;
  chatStore.page++;

  const res = await chatList({
    userId: userStore.userInfo.userId,
    type: 3,
    functionType: chatStore.menuId,
    pageSize,
    page: chatStore.page,
  });
  if (res.code != 0) return;
  const newData = res.data.filter((item) => item.dateType === "1");
  const oldData = res.data.filter((item) => item.dateType === "2");

  if (newData.length) {
    chatStore.menuList[0].list = chatStore.menuList[0].list.concat(newData);
  }
  if (oldData.length) {
    chatStore.menuList[1].list = chatStore.menuList[1].list.concat(oldData);
  }
};
// 监听滚动事件
const handleScroll = () => {
  const { scrollTop, clientHeight, scrollHeight } = scrollRef.value;
  if (scrollTop + clientHeight + 1 >= scrollHeight) {
    getChatList();
  }
};

let editingStatus = reactive<any>({});
// 切换
const tabChange = (id) => {
  iconIndex.value = id;
  Object.keys(editingStatus).forEach((key) => {
    editingStatus[key] = false;
  });
  router.push({
    path: "/chat",
    query: {
      id,
    },
  });
};

// 修改状态切换
const showEdit = throttle((id) => {
  if (!editingStatus[id]) {
    editingStatus[id] = false;
  }
  editingStatus[id] = !editingStatus[id];
}, 300);
// 修改数据
const editData = async (id: string, question: string) => {
  const res = await chatUpdate(id, question);
  if (res.code != 0) return;
  ElNotification({
    showClose: true,
    message: res.errorMessage,
    type: "success",
  });

  Object.keys(editingStatus).forEach((key) => {
    editingStatus[key] = false;
  });
};
// 删除
const deleteData = async (id: string) => {
  let routeId = 0;
  const res = await chatDelete(id);
  if (res.code !== 0) return;
  ElNotification({
    showClose: true,
    message: res.errorMessage,
    type: "success",
  });

  chatStore.menuList = chatStore.menuList.map((category) => ({
    ...category,
    list: category.list.filter((item) => item.id != id),
  }));

  if (chatStore.menuList[0].list.length) {
    routeId = chatStore.menuList[0].list[0].id;
  } else if (chatStore.menuList[1].list.length) {
    routeId = chatStore.menuList[1].list[0].id;
  } else {
    routeId = 0;
  }

  router.push({
    path: "/chat",
    query: {
      id: routeId,
    },
  });
};

import { useRoute } from "vue-router";
const route = useRoute();
// 监听路由
watch(
  route,
  (newVal) => {
    iconIndex.value = newVal.query.id;
  },
  { immediate: true, deep: true }
);
</script>
<style lang="scss" scoped>
.inner {
  position: relative;

  height: 100%;
  width: auto;
  .slide {
    box-sizing: border-box;
    width: 199px;
    height: 100%;

    display: flex;
    flex-direction: column;
    background-color: #f8f8fa;
    .slide-header {
      padding: 13px;
    }
    .middle-create-btn {
      height: 34px;
      width: 100%;
      cursor: pointer;
      background: #c90000;
      border-radius: 7px 7px 7px 7px;
      color: #fff;
      font-size: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      box-sizing: border-box;

      img {
        width: 11px;
        height: 11px;
      }
      p {
        margin-left: 10px;
      }
    }
    .slide-content {
      flex: 1;
      overflow: auto;
      .middle-list {
        margin-top: 10px;
        padding: 0 13px;
        p {
          color: #817f7f;
          font-size: 12px;
        }
        ul {
          li {
            box-sizing: border-box;
            width: 100%;
            background: #ffffff;
            height: 29px;
            line-height: 29px;
            border-radius: 6px 6px 6px 6px;

            margin-top: 10px;
            font-size: 12px;
            color: #664a4a;
            cursor: pointer;
            .item-not-edit {
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding: 0 10px;
              width: 100%;
              box-sizing: border-box;
              height: 100%;
              .item-left,
              .item-right {
                display: flex;
                align-items: center;
              }
              .item-left {
                flex: 1;
                height: 100%;
                min-width: 0;
                .item-left-text {
                  height: 100%;
                  min-width: 0;
                  p {
                    overflow: hidden; /* 隐藏超出部分 */
                    white-space: nowrap; /* 不换行 */
                    text-overflow: ellipsis; /* 显示省略号 */
                  }
                }
              }
            }
            .item-edit {
              position: relative;
              box-sizing: border-box;
              padding-left: 10px;
              input {
                height: 100%;
              }
              .img-container {
                position: absolute;
                right: 0;
                top: 0;
                display: flex;
                height: 100%;
                align-items: center;
                img {
                  width: 12px;
                  height: 12px;
                }
              }
            }
            img {
              width: 12px;
              height: 12px;
              margin-right: 5px;
            }
          }
          .active {
            border: 1px solid #cf0606;
          }
        }
      }
    }
    .slide-footer {
      width: 100%;
      margin-top: 11px;
      height: 29px;
      background: #ffffff;
      border-radius: 6px 6px 6px 6px;
      border: 1px solid #ccc;
    }
  }
  // 动画
  .slide-enter-active,
  .slide-leave-active {
    transition: all 0.5s ease;
  }
  .slide-enter-from,
  .slide-leave-to {
    transform: translateX(-100%);
  }
  .slide-enter-to,
  .slide-leave-from {
    transform: translateX(0);
  }
  .toggle {
    position: absolute;
    top: 75%;
    left: 0;
    cursor: pointer;
    z-index: 100;
    transform: translateX(185px) rotate(0);
    transition: transform 0.5s ease;
    img {
      width: 19px;
      height: 19px;
    }
  }
}
// 滚动条样式
.inner .slide-content::-webkit-scrollbar {
  width: 4px;
  height: 4px;
}
.inner .slide-content::-webkit-scrollbar-track {
  background-color: transparent;
}
.inner .slide-content::-webkit-scrollbar-thumb {
  border-radius: 6px;
  background-color: #e3e3e3;
}
.inner .slide-content::-webkit-scrollbar-thumb:hover {
  background-color: #c90006;
}
</style>
